<?php


namespace platform\models;


use Yii;

/**
 *
 * @property-read mixed $permissions
 * @property-read mixed $assignedRoles
 */
class User extends \common\models\User
{
    const CREATE_SCENARIO = 'create';
    const UPDATE_SCENARIO = 'update';

    public $password;

    public function rules()
    {
        return [
            [['username', 'password'], 'required', 'on' => 'create'],
            [['username', 'password'], 'trim'],
            [['username'], 'required', 'on' => 'update'],
            [['username'], 'string', 'min' => 2, 'max' => 20],
            [['status'], 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE]],
            [['status'], 'default', 'value' => self::STATUS_ACTIVE],
            [['remark'], 'string'],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();

        $scenarios[self::CREATE_SCENARIO] = [
            'username', 'password', 'status', 'remark'
        ];
        $scenarios[self::UPDATE_SCENARIO] = [
            'username', 'password', 'status', 'remark'
        ];

        return $scenarios;
    }

    public function fields()
    {
        return ['id', 'username', 'auth_key', 'status', 'remark', 'updated_at', 'created_at'];
    }

    public function extraFields()
    {
        return ['permissions'];
    }


    public function getPermissions()
    {
        $authManager = Yii::$app->authManager;
        return $authManager->getPermissionsByUser($this->id);
    }

    public function beforeSave($insert)
    {
        if ($insert) {
            $this->generateAuthKey();
        }

        if (!empty($this->password)) {
            $this->setPassword($this->password);
        }

        return parent::beforeSave($insert);
    }

    public function assign()
    {
        $authManager = Yii::$app->authManager;
        $roles = Yii::$app->request->post('roles');

        if (empty($roles)) {
            return;
        }

        foreach ($roles as $r) {
            $role = $authManager->getRole($r);
            $authManager->assign($role, $this->id);
        }
    }


    public function revoke()
    {
        $authManager = Yii::$app->authManager;
        $roles = Yii::$app->request->post('roles');

        if (empty($roles)) {
            return;
        }

        foreach ($roles as $r) {
            $role = $authManager->getRole($r);
            $authManager->revoke($role, $this->id);
        }
    }

    public function getAssignedRoles()
    {
        $authManager = Yii::$app->authManager;
        return $authManager->getRolesByUser($this->id);
    }
}